<?php

namespace app\admin\controller\xmwms;

use Exception;
use app\common\controller\Backend;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;

class Product extends Backend
{
     /**
      * @var \app\admin\model\xmwms\Product
      */
     protected object $model;

     protected string|array $defaultSortField = 'weigh,desc';

     protected string|array $preExcludeFields = ['id', 'create_time', 'update_time'];

     protected array $withJoinTable = ['wmsBrand', 'wmsCategory', 'wmsUnit', 'wmsWarehouse'];

     protected string|array $warningWithJoinTable = ['wmsBrand'];

     protected string|array $stockInquiryWithJoinTable = ['wmsBrand', 'wmsUnit'];

     protected string|array $quickSearchField = ['id', 'name'];

     public function initialize(): void
     {
          parent::initialize();
          $this->model = new \app\admin\model\xmwms\Product;
     }

     /**
      * 查看
      */
     public function index(): void
     {
          $this->request->filter(['strip_tags', 'trim']);
          // 如果是select则转发到select方法,若select未重写,其实还是继续执行index
          if ($this->request->param('select')) {
               $this->select();
          }
          list($where, $alias, $limit, $order) = $this->queryBuilder();

          $type = $this->request->param('type');
          if (isset($type) && !empty($type)) {
//            type: warehousingOrder outboundOrder
               if ($type == 'outboundOrder') {
                    $where[] = ['total_stock_num', '>', 0];
               }
               if ($type !== 'warehousingOrder') {
                    $where[] = ['product.total_stock_num', '>', '0'];
               }
               $where[] = ['product.status', '=', '10'];
          }

          $res = $this->model
               ->withJoin($this->withJoinTable, $this->withJoinType)
               ->alias($alias)
               ->where($where)
               ->order($order)
               ->paginate($limit);
          $res->visible(['wmsBrand' => ['name'], 'wmsCategory' => ['name'], 'wmsUnit' => ['name'], 'wmsWarehouse' => ['name']]);

          $this->success('', [
               'list' => $res->items(),
               'total' => $res->total(),
               'remark' => get_route_remark(),
          ]);
     }

     public function add(): void
     {
          if ($this->request->isPost()) {
               $data = $this->request->post();
               if (!$data) {
                    $this->error(__('Parameter %s can not be empty', ['']));
               }

               $data = $this->excludeFields($data);
               if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $data[$this->dataLimitField] = $this->auth->id;
               }

               $warehouse_type = \app\admin\model\xmwms\Warehouse::where('id', $data['warehouse_shelf_id'])->value('warehouse_type');
               if ($warehouse_type !== 'warehouse_shelf') {
                    $this->error('请选择正确的货架');
               }
               $result = false;
               Db::startTrans();
               try {
                    // 模型验证
                    if ($this->modelValidate) {
                         $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                         if (class_exists($validate)) {
                              $validate = new $validate;
                              if ($this->modelSceneValidate) $validate->scene('add');
                              $validate->check($data);
                         }
                    }
                    if (empty($data['product_no'])) {
                         $data['product_no'] = date('YmdHis') . rand(100000, 999999);
                    }
                    $result = $this->model->save($data);
                    Db::commit();
               } catch (ValidateException|PDOException|Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
               }
               if ($result !== false) {
                    $this->success(__('Added successfully'));
               } else {
                    $this->error(__('No rows were added'));
               }
          }

          $this->error(__('Parameter error'));
     }

     public function edit(): void
     {
          $id = $this->request->param($this->model->getPk());
          $row = $this->model->find($id);
          if (!$row) {
               $this->error(__('Record not found'));
          }

          $dataLimitAdminIds = $this->getDataLimitAdminIds();
          if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
               $this->error(__('You have no permission'));
          }

          if ($this->request->isPost()) {
               $data = $this->request->post();
               if (!$data) {
                    $this->error(__('Parameter %s can not be empty', ['']));
               }

               $warehouse_type = \app\admin\model\xmwms\Warehouse::where('id', $data['warehouse_shelf_id'])->value('warehouse_type');
               if ($warehouse_type !== 'warehouse_shelf') {
                    $this->error('请选择正确的货架');
               }

               $data = $this->excludeFields($data);
               $result = false;
               Db::startTrans();
               try {
                    // 模型验证
                    if ($this->modelValidate) {
                         $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                         if (class_exists($validate)) {
                              $validate = new $validate;
                              if ($this->modelSceneValidate) $validate->scene('edit');
                              $validate->check($data);
                         }
                    }
                    $result = $row->save($data);
                    Db::commit();
               } catch (ValidateException|PDOException|Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
               }
               if ($result !== false) {
                    $this->success(__('Update successful'));
               } else {
                    $this->error(__('No rows updated'));
               }

          }

          $this->success('', [
               'row' => $row
          ]);
     }


     public function warning(): void
     {
          list($where, $alias, $limit) = $this->queryBuilder();
          $res = $this->model
               ->withJoin($this->warningWithJoinTable, $this->withJoinType)
               ->alias($alias)
               ->whereColumn('safety_stock_num', '>=', 'total_stock_num')
               ->where('total_stock_num', '>', 0)->where('status', 10)
               ->order('total_stock_num desc')
               ->paginate($limit);
          $res->visible(['wmsBrand' => ['name']]);

          $this->success('', [
               'list' => $res->items(),
               'total' => $res->total(),
               'remark' => get_route_remark(),
          ]);
     }


     public function stockInquiry(): void
     {
          $this->request->filter(['strip_tags', 'trim']);
          // 如果是select则转发到select方法,若select未重写,其实还是继续执行index
          if ($this->request->param('select')) {
               $this->select();
          }

          list($where, $alias, $limit, $order) = $this->queryBuilder();
          $res = $this->model
               ->withJoin($this->stockInquiryWithJoinTable, $this->withJoinType)
               ->alias($alias)
               ->where($where)
               ->order($order)
               ->paginate($limit);
          $res->visible(['wmsBrand' => ['name'], 'wmsUnit' => ['name']]);

          $this->success('', [
               'list' => $res->items(),
               'total' => $res->total(),
               'remark' => get_route_remark(),
          ]);
     }


}
